package com.carbohydrate42.kotlin_compose_demo.config

import android.util.Log
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.sqlite.db.SupportSQLiteDatabase
import com.carbohydrate42.kotlin_compose_demo.MainApplication
import com.carbohydrate42.kotlin_compose_demo.constant.Common
import com.carbohydrate42.kotlin_compose_demo.dao.UserDao
import com.carbohydrate42.kotlin_compose_demo.entity.User

@Database(
    version = 1,
    exportSchema = false,
    entities = [
        // 实体类放这里
        User::class
    ]
)
abstract class TestDatabase : RoomDatabase() {
    // DAO 放这里
    abstract fun userDao(): UserDao
}

class RoomConfig {
    companion object {
        private const val DB_NAME = "test_database.db"
        // todo: application context 如何更好的获取

        val testDatabase: TestDatabase = Room
            // 如果 databaseBuilder 改为 inMemoryDatabaseBuilder 则创建一个内存数据库（进程销毁后，数据丢失）
            .databaseBuilder(
                MainApplication.getContext(),
                TestDatabase::class.java,
                DB_NAME
            )
            .addCallback(object : RoomDatabase.Callback() {
                override fun onCreate(db: SupportSQLiteDatabase) {
                    super.onCreate(db)
                    Log.d(Common.ANDROID_LOG_TAG.label, "room orm onCreate")
                }
            })
            //是否允许在主线程进行查询
            .allowMainThreadQueries()
            //数据库升级异常之后的回滚
            .fallbackToDestructiveMigration()
            .build()

    }
}


